package com.qilu.pe.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qilu.pe.R;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Global;
import com.qilu.pe.dao.bean.EventModel;
import com.qilu.pe.dao.bean.Patient;
import com.qilu.pe.dao.bean.PatientUserInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.GlideUtil;
import com.qilu.pe.support.util.PeUtil;
import com.qilu.pe.ui.activity.PatientDetailActivity;
import com.qilu.pe.ui.activity.PatientInfoInputActivity;
import com.qilu.pe.ui.activity.PatientListActivity;
import com.qilu.pe.ui.activity.PlaceOrderActivity;
import com.qilu.pe.ui.activity.ReportCheckActivity;
import com.qilu.pe.ui.activity.TodayTestActivity;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ToastUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

// 患者
public class Home2Fragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    private SmartRefreshLayout vRefresh;
    private RecyclerView rcv_list;// 近期患者列表
    private RelativeLayout rl_3, rl_4;// 患者信息录入,近期就诊患者
    private RelativeLayout rl_today_test, rl_test_report;// 今日检验 检验报告
    private TextView tv_name, tv_phone, tv_addr;
    private RoundedImageView iv_header;// 左上角的头像

    private int mPage = 1;
    private int mPageSize = 15;
    private PatientListAdapter adapter;
    private List<Patient> patientList = new ArrayList<>();
    private static Home2Fragment fragment;


    public Home2Fragment() {

    }

    public static Home2Fragment newInstance() {
        if (fragment == null) {
            fragment = new Home2Fragment();
            Bundle args = new Bundle();
            fragment.setArguments(args);
        }
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMsg(EventModel ev) {
        if (ev.getEventCode() == 20101452) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    tv_addr.setText(Global.ORG_ADDRESS);
                }
            }, 100);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home2, container, false);
        rcv_list = v.findViewById(R.id.rcv_list);
        rl_3 = v.findViewById(R.id.rl_3);
        rl_4 = v.findViewById(R.id.rl_4);
        rl_today_test = v.findViewById(R.id.rl_today_test);
        rl_test_report = v.findViewById(R.id.rl_test_report);
        tv_name = v.findViewById(R.id.tv_name);
        tv_phone = v.findViewById(R.id.tv_phone);
        tv_addr = v.findViewById(R.id.tv_addr);
        iv_header = v.findViewById(R.id.iv_header);
        vRefresh = v.findViewById(R.id.vRefresh);

        adapter = new PatientListAdapter(getActivity());
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rcv_list.setLayoutManager(manager);
        rcv_list.setAdapter(adapter);
        adapter.setDataList(patientList);

        setListeners();

        reqPatietentTopUserInfo();// 上面的用户信息

        vRefresh.setNestedScrollingEnabled(true);
        vRefresh.setDragRate(1f);
        vRefresh.setHeaderTriggerRate(0.5f);
        vRefresh.setOnRefreshListener(this);
        vRefresh.setOnLoadMoreListener(this);
        vRefresh.autoRefresh();
        return v;
    }

    // 请求患者顶部的用户信息
    private Disposable reqPatietentTopUserInfo() {
        return APIRetrofit.getDefault().reqPatientTopUserInfo(Global.HEADER)
                .compose(RxUtil.<BaseResult2<PatientUserInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<PatientUserInfo>>() {
                    @Override
                    public void accept(BaseResult2<PatientUserInfo> result2) throws Exception {
                        hideProgress();

                        PatientUserInfo userInfo = result2.getData();
                        tv_name.setText(userInfo.getName());
                        tv_phone.setText(userInfo.getPhone());
                        tv_addr.setText(userInfo.getAddress());
                        GlideUtil.loadImg(PeUtil.getImageUrl(userInfo.getPicture()), iv_header);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPage = 1;
        patientList.clear();
        adapter.clear();
        vRefresh.setEnableLoadMore(true);
        onLoadMore(refreshLayout);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        APIRetrofit.getDefault().reqRecentPatientList(Global.HEADER, mPage, mPageSize, 0)
                .compose(RxUtil.<BaseResult2<List<Patient>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<Patient>>>() {
                    @Override
                    public void accept(BaseResult2<List<Patient>> result2) throws Exception {
                        hideProgress();
                        vRefresh.finishRefresh();
                        vRefresh.finishLoadMore();
                        if (result2.isSuccess()) {
                            mPage++;
                            patientList.addAll(result2.getData());
                            adapter.setDataList(patientList);
                            adapter.notifyDataSetChanged();
                            if (result2.getData() == null || result2.getData().size() == 0) {
                                vRefresh.setEnableLoadMore(false);
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private void setListeners() {
        setOnClickListener(rl_3, rl_4, rl_today_test, rl_test_report);
        adapter.setOnItemClickListener(new ListBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("patient", patientList.get(position));
                startActivity(PatientDetailActivity.class, bundle);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v == rl_4) {// 近期就诊患者
            startActivity(PatientListActivity.class);
        }
        if (v == rl_3) {
            startActivity(PatientInfoInputActivity.class);
        }
        if (v == rl_today_test) {// 今日检验
            Bundle bundle = new Bundle();
//            bundle.putString("patientId",);
            startActivity(TodayTestActivity.class);
        }
        if (v == rl_test_report) {// 检验报告
            startActivity(ReportCheckActivity.class);
        }
    }

    private class PatientListAdapter extends ListBaseAdapter<Patient> {

        public PatientListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_patient_list;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            RoundedImageView iv_header = holder.getView(R.id.iv_header);
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_phone = holder.getView(R.id.tv_phone);
            TextView tv_date = holder.getView(R.id.tv_date);
            TextView tv_order = holder.getView(R.id.tv_order);
            LinearLayout ll_tag = holder.getView(R.id.ll_tag);

            final Patient p = mDataList.get(position);

            GlideUtil.loadImg(p.getPicture(), iv_header);
            tv_name.setText(p.getName());
            tv_phone.setText(p.getPhone());
            tv_date.setText(p.getCreated_at());

            ll_tag.removeAllViews();
            if (p.getMedical() != null) {
                String[] medicalArray = p.getMedical().split(",");
                for (int i = 0; i < medicalArray.length; i++) {
                    ll_tag.addView(createTagView(getContext(), i, medicalArray[i]));
                }
            }

            // 立即预约
            tv_order.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("patient", p);
                    startActivity(PlaceOrderActivity.class, bundle);
                }
            });
        }

        public TextView createTagView(Context context, int index, String tagStr) {
            TextView tag = new TextView(context);
            tag.setHeight(SizeUtils.dp2px(26f));
            tag.setBackgroundResource(R.drawable.shape_special_tag_bg);
            tag.setGravity(Gravity.CENTER);
            tag.setPadding(SizeUtils.dp2px(10), 0, SizeUtils.dp2px(10), 0);
            tag.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
            tag.setTextSize(14f);
            tag.setText(tagStr);
            if (index > 0) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.leftMargin = SizeUtils.dp2px(10f);
                tag.setLayoutParams(params);
            }
            return tag;
        }
    }
}